package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmUserLoginVo;
import com.heima.model.wemedia.vo.WmUserVo;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        //正常登录查询手机号和密码
        WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();
        if (wmUser == null) {
            return ResponseResult.okResult(1002, "用户不存在");
        }

        //把查询到的用户信息设置到threadlocal中
        //WmThreadLocalUtil.setUser(wmUser);

        boolean checkpw = BCrypt.checkpw(dto.getPassword(), wmUser.getPassword());
        if (checkpw == false) {
            return ResponseResult.okResult(2, "密码错误");
        }
        //用户存在,生成JWT
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        //封装返回结果
        WmUserVo wmUserVo = new WmUserVo();
        BeanUtils.copyProperties(wmUser, wmUserVo);
        wmUserVo.setPassword("");
        WmUserLoginVo wmUserLoginVo = new WmUserLoginVo();
        wmUserLoginVo.setUser(wmUserVo);
        wmUserLoginVo.setToken(token);
        return ResponseResult.okResult(wmUserLoginVo);
    }
}